// recent-commit.js
import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
async function displayRecentCommit() {
    try {
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        await setupUserProfile(username);
        const practiceId = urlParams.get('practiceId');
        const response = await fetch(`/user-info?username=${username}`);
        const data = await response.json();
        const userId = data.user_id;
        if (!username || !practiceId) {
            throw new Error('缺少必要的参数');
        }


        // 获取练习详情
        const practiceDetail = await fetchPracticeDetail(practiceId, userId);
        document.getElementById('practice-title').textContent = practiceDetail.practice_name;
        document.getElementById('course-info').textContent = `所属课程：${practiceDetail.course_name}`;

        // 获取题目答案
        const questionsContainer = document.getElementById('questions-container');
        questionsContainer.innerHTML = '';

        // 获取所有类型的题目
        const [choiceQuestions, fillQuestions, essayQuestions] = await Promise.all([
            fetchChoiceQuestions(practiceId, userId),
            fetchFillQuestions(practiceId, userId),
            fetchEssayQuestions(practiceId, userId)
        ]);

        // 为每种类型的题目添加type字段以便区分
        const choiceQuestionsWithType = choiceQuestions.map(q => ({...q, type: 'choice'}));
        const fillQuestionsWithType = fillQuestions.map(q => ({...q, type: 'fill'}));
        const essayQuestionsWithType = essayQuestions.map(q => ({...q, type: 'essay'}));

        // 合并所有题目并按题号排序
        const allQuestions = [
            ...choiceQuestionsWithType,
            ...fillQuestionsWithType,
            ...essayQuestionsWithType
        ].sort((a, b) => a.question_order - b.question_order);

        // 按排序后的顺序显示所有题目
        for (const question of allQuestions) {
            switch(question.type) {
                case 'choice':
                    await displaySingleChoiceQuestion(question, questionsContainer, practiceId, userId);
                    break;
                case 'fill':
                    await displaySingleFillQuestion(question, questionsContainer, practiceId, userId);
                    break;
                case 'essay':
                    await displaySingleEssayQuestion(question, questionsContainer, practiceId, userId);
                    break;
            }
        }


        // 添加返回按钮事件
        document.getElementById('back-btn').addEventListener('click', () => {
            window.location.href = 'todo-practice.html' + window.location.search;
        });
    } catch (error) {
        console.error('加载最近提交记录失败:', error);
        alert(`加载最近提交记录失败: ${error.message}`);
    }
}

// 获取练习详情
async function fetchPracticeDetail(practiceId, userId) {
    const response = await fetch(`/practice/detail/${practiceId}?userId=${userId}`);
    const practice = await response.json();

    // 获取课程信息
    const courseResponse = await fetch(`/get-course/${practice.course_code}`);
    const course = await courseResponse.json();

    return { ...practice, course_name: course.course_name };
}

async function fetchChoiceQuestions(practiceId, userId) {
    const response = await fetch(`/api/choice-questions/${practiceId}?userId=${userId}`);
    return await response.json();
}

async function fetchFillQuestions(practiceId, userId) {
    const response = await fetch(`/api/fill-questions/${practiceId}?userId=${userId}`);
    return await response.json();
}

async function fetchEssayQuestions(practiceId, userId) {
    const response = await fetch(`/api/essay-questions/${practiceId}?userId=${userId}`);
    return await response.json();
}

async function displaySingleChoiceQuestion(question, container, practiceId, userId) {
    const response = await fetch(`/check-question-collection?practiceId=${practiceId}&userId=${userId}&questionOrder=${question.question_order}`);
    const data = await response.json();
    let isCollected = data.isCollected;
    const questionCard = document.createElement('div');
    questionCard.className = 'question-card';

    // 使用新的卡片样式，增强已选选项的视觉效果
    questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-blue-50 rounded-xl border border-blue-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">选择题</h3>
            <span class="bg-white text-blue-600 rounded-full px-3 py-1 text-sm font-medium">${question.question_order + 1}</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-4 leading-relaxed">
            ${escapeHTML(question.question)}
        </div>
        
        <ul class="space-y-3">
            ${['A', 'B', 'C', 'D'].map(option => {
                const isSelected = question.user_answer === option;
                
                // 为选中的选项添加更明显的高亮效果
                let optionClass = 'flex items-start p-3 rounded-lg border';
                let bgClass = 'bg-white/80';
                let iconClass = 'fa-circle text-gray-300';
                let selectedIndicator = '';
                
                if (isSelected) {
                    optionClass += ' border-blue-300 shadow';
                    bgClass = 'bg-blue-50';  // 更明显的背景色
                    iconClass = 'fa-check-circle text-blue-500';  // 使用对勾图标
                    selectedIndicator = '<span class="ml-2 text-blue-600 font-medium">已选择</span>';
                } else {
                    optionClass += ' border-blue-100';
                }
                
                return `
                <li class="${optionClass} ${bgClass}">
                    <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">${option}</span>
                    <span class="flex-1">${escapeHTML(question[`option_${option.toLowerCase()}`])}</span>
                    <div class="flex items-center">
                        <i class="fa-solid ${iconClass} text-lg"></i>
                        ${selectedIndicator}
                    </div>
                </li>
                `;
            }).join('')}
        </ul>
    </div>
</div>
    `;

    // 创建收藏按钮容器
    const collectSection = document.createElement('div');
    collectSection.className = 'collect-section mt-4 flex justify-end';

    // 创建并添加收藏按钮
    const collectButton = createCollectButton(question, practiceId, userId, isCollected);
    collectSection.appendChild(collectButton);

    // 将收藏按钮容器添加到问题卡片
    questionCard.appendChild(collectSection);

    // 将问题卡片添加到容器
    container.appendChild(questionCard);
}

//HTML转义函数
function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    if (!str) return '';
    return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}
async function displaySingleFillQuestion(question, container, practiceId, userId) {
    const response = await fetch(`/check-question-collection?practiceId=${practiceId}&userId=${userId}&questionOrder=${question.question_order}`);
    const data = await response.json();
    let isCollected = data.isCollected;
    const questionCard = document.createElement('div');
    questionCard.className = 'question-card';

    // 解析填空题的空
    const blanks = [];
    let blankCount = 0;
    
    // 计算空白数量并生成问题文本
    const formattedQuestion = question.question.replace(/__/g, () => {
        blankCount++;
        return `<span class="inline-block mx-1 px-3 py-1 bg-blue-100 border border-blue-200 rounded text-sm font-medium">填空${blankCount}</span>`;
    });

    // 获取所有空的答案
    for (let i = 1; i <= blankCount; i++) {
        const hasUserAnswer = question[`commited_answer${i}`] !== undefined && question[`commited_answer${i}`] !== null;
        
        blanks.push({
            userAnswer: question[`commited_answer${i}`],
            hasUserAnswer: hasUserAnswer
        });
    }

    // 生成填空答案HTML
    let blanksHtml = '';
    blanks.forEach((blank, blankIndex) => {
        // 答案状态样式
        let answerClass = 'flex items-start bg-white/80 p-3 rounded-lg border';
        let iconClass = 'fa-circle text-gray-300';
        let indicatorText = '';
        
        if (blank.hasUserAnswer) {
            answerClass += ' bg-blue-50 border-blue-300 shadow';
            iconClass = 'fa-pencil text-blue-500';
            indicatorText = '<span class="text-blue-600 font-medium">已填写</span>';
        } else {
            answerClass += ' border-blue-100';
            indicatorText = '<span class="text-gray-500 italic">未填写</span>';
        }
        
        blanksHtml += `
            <div class="${answerClass}">
                <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">空${blankIndex + 1}</span>
                <div class="flex-1">
                    <div class="flex items-center">
                        <p>${blank.hasUserAnswer ? blank.userAnswer : indicatorText}</p>
                    </div>
                </div>
                <div class="flex items-center">
                    <i class="fa-solid ${iconClass} text-lg"></i>
                </div>
            </div>
        `;
    });

    // 设置HTML内容
    questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-green-50 rounded-xl border border-green-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-green-500 to-green-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">填空题</h3>
            <span class="bg-white text-green-600 rounded-full px-3 py-1 text-sm font-medium">${question.question_order + 1}</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-6 leading-relaxed">
            ${formattedQuestion}
        </div>
        
        <div class="answer-section">
            <div class="answer-label text-gray-600 font-medium mb-3">你的答案：</div>
            <div class="space-y-3">
                ${blanksHtml}
            </div>
        </div>
    </div>
</div>
    `;

    // 创建收藏按钮容器
    const collectSection = document.createElement('div');
    collectSection.className = 'collect-section mt-4 flex justify-end';

    // 创建并添加收藏按钮
    const collectButton = createCollectButton(question, practiceId, userId, isCollected);
    collectSection.appendChild(collectButton);

    // 将收藏按钮容器添加到问题卡片
    questionCard.appendChild(collectSection);

    // 将问题卡片添加到容器
    container.appendChild(questionCard);
}

async function displaySingleEssayQuestion(question, container, practiceId, userId) {
    const response = await fetch(`/check-question-collection?practiceId=${practiceId}&userId=${userId}&questionOrder=${question.question_order}`);
    const data = await response.json();
    let isCollected = data.isCollected;
    const questionCard = document.createElement('div');
    questionCard.className = 'question-card';

    // 设置HTML内容
    questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-purple-50 rounded-xl border border-purple-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">解答题</h3>
            <span class="bg-white text-purple-600 rounded-full px-3 py-1 text-sm font-medium">${question.question_order + 1}</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-4 leading-relaxed">
            ${escapeHTML(question.question)}
        </div>
        
        <div class="answer-section">
            <div class="answer-label text-gray-600 font-medium mb-3">你的答案：</div>
            <div class="bg-white/80 p-4 rounded-lg border border-purple-100 mb-4">
                ${question.user_answer 
                    ? `<p class="text-gray-700">${escapeHTML(question.user_answer)}</p>` 
                    : '<p class="text-gray-500 italic">未填写</p>'}
            </div>
        </div>
    </div>
</div>
    `;

    // 创建收藏按钮容器
    const collectSection = document.createElement('div');
    collectSection.className = 'collect-section mt-4 flex justify-end';

    // 创建并添加收藏按钮
    const collectButton = createCollectButton(question, practiceId, userId, isCollected);
    collectSection.appendChild(collectButton);

    // 将收藏按钮容器添加到问题卡片
    questionCard.appendChild(collectSection);

    // 将问题卡片添加到容器
    container.appendChild(questionCard);
}

// 页面加载完成后显示最近提交记录
window.onload = displayRecentCommit;

const backButton = document.querySelector('li a[href="#"]');

// 添加点击事件监听器
backButton.addEventListener('click', function(event) {
    // 阻止默认行为（防止跳转至 #）
    event.preventDefault();

    // 跳转到todo-practice.html并保留查询参数
    window.location.href = 'todo-practice.html' + window.location.search;
});

function createCollectButton(question, practiceId, userId,isCollected) {
    const button = document.createElement('button');
    button.className = 'collect-btn';

    // 更新按钮外观的函数
    function updateButtonUI() {
        const starIcon = isCollected
            ? '<i class="fa-solid fa-star text-red-500"></i>'
            : '<i class="fa-regular fa-star text-gray-400"></i>';

        const buttonText = isCollected ? '取消收藏' : '收藏题目';
        button.innerHTML = `${starIcon} ${buttonText}`;
    }

    // 初始化按钮外观
    updateButtonUI();
    button.style.color = 'gray';

    button.addEventListener('click', async () => {
        try {
            let response, data;

            if (isCollected) {
                // 取消收藏
                response = await fetch('/uncollect-question', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        practiceId,
                        userId,
                        questionOrder: question.question_order
                    })
                });

                data = await response.json();

                if (response.ok) {
                    isCollected = false; // 更新状态
                    updateButtonUI();    // 更新UI
                } else {
                    alert(data.message);
                }
            } else {
                // 收藏题目
                response = await fetch('/collect-question', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        practiceId,
                        userId,
                        questionOrder: question.question_order
                    })
                });

                data = await response.json();

                if (response.ok) {
                    isCollected = true;  // 更新状态
                    updateButtonUI();    // 更新UI
                } else {
                    alert(data.message);
                }
            }
        } catch (error) {
            console.error('收藏操作失败:', error);
            alert('操作失败，请稍后重试');
        }
    });

    return button;
}

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='todo-practice.html'+window.location.search;
        });
    }
});

document.getElementById('header-back-btn').addEventListener('click', () => {
    window.location.href = 'todo-practice.html' + window.location.search;
});


export{
    displayRecentCommit,
    fetchPracticeDetail,
    fetchChoiceQuestions,
    fetchFillQuestions,
    fetchEssayQuestions,
    displaySingleChoiceQuestion,
    displaySingleFillQuestion,
    displaySingleEssayQuestion,
    escapeHTML,
    createCollectButton,
}